package com.gzw.dms.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.CheckPermission;
import com.gzw.dms.base.PermissionActivity;
import com.gzw.dms.bean.Constant;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;
import java.util.HashMap;
import java.util.Map;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity {
    private AutoCompleteTextView actv_userName;
    private EditText et_password;
    private Button btn_login;
    private LoginTask loginTask;
    private ProgressDialog mProgressDialog;
    private Context mContext;
    private Toolbar toolbar;
    private TextView tv_set_ip;
    private Boolean isrunning = false;
    private static final int CANCELLED = 3;
    private long exitTime=0;
    private static final int REQUEST_CODE = 0;//请求码

    private CheckPermission checkPermission;//检测权限器

    //配置需要取的权限
    static final String[] PERMISSION = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
            Manifest.permission.READ_EXTERNAL_STORAGE,  //读取权限
            Manifest.permission.CAMERA,//相机权限
            Manifest.permission.READ_PHONE_STATE,//手机状态
            Manifest.permission.ACCESS_COARSE_LOCATION,//位置信息
            Manifest.permission.ACCESS_FINE_LOCATION, //
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        actv_userName = (AutoCompleteTextView) findViewById(R.id.actv_userName);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        tv_set_ip = (TextView) findViewById(R.id.tv_set_ip);
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("登录");
        toolbar.setNavigationIcon(null);
        setSupportActionBar(toolbar);
        actv_userName.setText(MyApplication.getUserInfo().getUsername());
//        et_password.setText(MyApplication.getUserInfo().getPassword());
        readUserContent();
        checkPermission = new CheckPermission(this);

    }

    @Override
    protected void initEvents() {
        btn_login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Login();
            }
        });
//        tv_set_ip.setOnClickListener(new myOnClick());
    }


    class myOnClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {

                case R.id.tv_set_ip:
                    Intent mIntent = new Intent();
//                    mIntent.setClass(mContext, HomeActivity.class);
                    mIntent.setClass(mContext, SetIpActivity.class);
                    startActivity(mIntent);
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        //缺少权限时，进入权限设置页面
        if (checkPermission.permissionSet(PERMISSION)) {
            startPermissionActivity();
        }
    }

    //进入权限设置页面
    private void startPermissionActivity() {
        PermissionActivity.startActivityForResult(this, REQUEST_CODE, PERMISSION);
    }

    //返回结果回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拒绝时，没有获取到主要权限，无法运行，关闭页面
        if (requestCode == REQUEST_CODE && resultCode == PermissionActivity.PERMISSION_DENIEG) {
            finish();
        }
    }

    private void Login() {

        if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED) {           loginTask.cancel(true);
             loginTask.cancel(true);
             mProgressDialog.dismiss();

//            return;
        }
        actv_userName.setError(null);
        et_password.setError(null);

        String userName = actv_userName.getText().toString();
        String password = et_password.getText().toString();

        boolean cancel = false;
        View focusView = null;
        //判断密码是为空 或者太短
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            et_password.setError(getString(R.string.error_invalid_password));
            focusView = et_password;
            cancel = true;
        }
        //判断账号是否为空 或者不符合规则
        if (TextUtils.isEmpty(userName)) {
            actv_userName.setError(getString(R.string.error_field_required));

            focusView = actv_userName;
            cancel = true;
        }

        if (cancel) {

        } else {
//            focusView.requestFocus();
            loginTask = new LoginTask();
            loginTask.execute(userName, password);
        }

    }

    //    private boolean isEmailValid(String email) {
//        return email.contains("@");
//    }
    private boolean isPasswordValid(String password) {
        return password.length() > 2;
    }

    public class LoginTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            isrunning = true;
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);

        }

        protected String doInBackground(String... params) {
            if (isCancelled())
            {
//                publishProgress(CANCELLED); //Notify your activity that you had canceled the task
                return (null); // don't forget to terminate this method
            }
            Map<String, String> map = new HashMap<>();
            map.put("userName", params[0]);
            map.put("pwd", params[1]);
            map.put("type", "new");
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appLogin"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            loginTask = null;
            isrunning = false;
            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接服务器异常");
            }
            if (result.indexOf("successMsg") > 0) {
                String successMsg = JsonUtil.getMsg(result, "successMsg");
                UserInfo userInfo = JsonUtil.getPerson(successMsg, UserInfo.class);
                saveUserContent(userInfo);
                startActivity(new Intent(LoginActivity.this, Home1Activity.class));
                finish();
//                //1.司机用户 2.供应商用户 3.其它
//                if (userInfo.getFlag().equals("1")) {
//                    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
//                    finish();
//                }
//               else if (userInfo.getFlag().equals("2")) {
//                    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
//                    finish();
//                }else {
//                    actv_userName.setError("该账户不能登录App!");
//                   T.showShort(mContext,"该账户不能登录App!");
//                }

            } else if (result.indexOf("errorMsg") > 0) {
                et_password.setError( JsonUtil.getMsg(result,"errorMsg"));
                et_password.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            loginTask = null;
        }
    }

    private void saveUserContent(UserInfo userInfo) {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        MyApplication.setIsUserLogin(true);
        MyApplication.setUserInfo(userInfo);
        edit.putString(Constant.USER_NAME_KEY, userInfo.getUsername());
        edit.putString(Constant.USER_ID_KEY, userInfo.getId());
        edit.putString(Constant.NAME_KEY, userInfo.getRealName());
        edit.putString(Constant.DRIVER_ID_KEY, userInfo.getDriver_id());
        edit.putBoolean(Constant.IS_USER_LOGIN_KEY, true);
        edit.putString(Constant.SUPPLIERS_ID_KEY, userInfo.getSuppliers_id());
        edit.putString(Constant.FLAG_KEY, userInfo.getFlag());
        edit.putString("userPhone",userInfo.getUserPhone());
        edit.putString("customerName",userInfo.getCustomer_name());
        edit.putString("did",userInfo.getDid());

        //本地存储list
        Gson gson = new Gson();
         String list  = gson.toJson(userInfo.getUserAppRole());
        edit.putString("role",list );
        String userIf  = gson.toJson(userInfo);
        edit.putString("userinfo",userIf);
//        edit.putString(Constant.PASSWORD_KEY,et_password.getText().toString().trim());

        edit.putString("passWord", et_password.getText().toString().trim());
        edit.commit();
    }

    private void readUserContent() {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                Context.MODE_PRIVATE);
        UserInfo userInfo = new UserInfo();
        userInfo.setPassword(sharedPreferences.getString("passWord", ""));
//        userInfo.setUsername(sharedPreferences.getString(Constant.USER_NAME_KEY, ""));
        et_password.setText(userInfo.getPassword().toString().trim());
    }



    @Override
    protected void onStop() {
        super.onStop();
        if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED) {
            loginTask.cancel(true);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序。", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

